package me.android.library.utils.android;

import android.database.Cursor;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import lombok.experimental.UtilityClass;
import mylab.utils.common.SqlStringUtil;

@UtilityClass
public class SqliteUtil {

    public <T> Collection<T> cursorToBeans(Cursor cursor, Class<T> beanClass) {
        List<T> list = Lists.newArrayList();
        // 使用 for 循环明确控制次数
        for (int i = 0; i < cursor.getCount(); i++) {
            if (cursor.moveToPosition(i)) {
                T bean = cursorToBean(cursor, beanClass);
                if (bean != null) {
                    list.add(bean);
                }
            }
        }

        return list;
    }

    public <T> T cursorToBean(Cursor cursor, Class<T> beanClass) {
        Map<String, Object> map = cursorToMap(cursor);
        if (CollectionUtil.isEmpty(map)) {
            return null;
        }

        return BeanUtil.toBean(map, beanClass);
    }

    public Map<String, Object> cursorToMap(Cursor cursor) {
        if (cursor == null || cursor.getCount() == 0 ) {
            return Collections.emptyMap();
        }

        Map<String, Object> map = Maps.newHashMap();
        int colCount = cursor.getColumnCount();
        for (int i = 0; i < colCount; i++) {
            String colName = SqlStringUtil.underlineToCamel(cursor.getColumnName(i));
            int type = cursor.getType(i);
            Object value = null;
            switch (type) {
                case Cursor.FIELD_TYPE_NULL -> value = null;
                case Cursor.FIELD_TYPE_INTEGER -> value = cursor.getLong(i);
                case Cursor.FIELD_TYPE_FLOAT -> value = cursor.getFloat(i);
                case Cursor.FIELD_TYPE_STRING -> value = cursor.getString(i);
                case Cursor.FIELD_TYPE_BLOB -> value = cursor.getBlob(i);
                default -> value = cursor.getString(i);
            }

            map.put(colName, value);
        }
        return map;
    }

}

